<?php
/**
 * @description:定时器酷控全量媒资入库
 * @author:xinxin.deng
 * @date: 2017/9/13 14:25
 */
header("Content-type: text/html; charset=utf-8");
ini_set('display_errors', 1);
set_time_limit(0);
include_once dirname(dirname(__FILE__)) . '/mgtv_v2/mgtv_init.php';
include_once dirname(dirname(__FILE__)) . '/api_v2/nn_const.php';
include_once dirname(dirname(__FILE__)) . '/api_v2/common.php';
include_once dirname(dirname(__FILE__)) . '/nn_logic/nl_common.func.php';
include_once dirname(dirname(__FILE__)) . '/v2/ns_core/m_split_xml_file.class.php';

class timer_execute extends nn_timer
{
    public $str_date = null;
    public $str_date_time = null;
    public $arr_full_assets_site = array();
    private $state = null;//默认状态，0未使用，1未补全，2已补全
    /**
     * 定时器初始化
     * @see nn_timer::action()
     */
    public function action($params = null)
    {
        $this->msg('开始执行...');
        $this->init($params);
        $this->msg('执行结束...');
    }
    
    /**
     * 初始化
     */
    public function init($params=null)
    {
        include_once dirname(dirname(__FILE__)) . '/nn_logic/full_assets/full_assets.class.php';
        include_once dirname(dirname(__FILE__)) . '/nn_logic/full_assets/full_assets_site.class.php';
        include_once dirname(dirname(__FILE__)) . '/api_v2/control/standard/sync_source.php';
        $str_third_playbill_pool = $params["bk_queue_value"];
        if(strlen($str_third_playbill_pool) <1)
        {
            $this->msg("[redis节目单池中返回数据为空]".$str_third_playbill_pool);
            return ;
        }
        if (strlen($this->arr_params['bk_queue_config']['nns_ext_info']['cp_id']) < 1)
        {
            $this->msg("[第三方请求全量数据CP ID为空为空]".var_export($this->arr_params, true));
            return ;
        }
        $cp_id = $this->arr_params['bk_queue_config']['nns_ext_info']['cp_id'];

        $result_cp = nl_cp::query_by_id($this->obj_dc, $cp_id);
        if($result_cp['ret'] !=0 || !isset($result_cp['data_info']) || !is_array($result_cp['data_info']) || empty($result_cp['data_info']))
        {
            $this->msg("[第三方请求全量数据CP ID不存在]".var_export($this->arr_params, true));
            return ;
        }
        $str_content = file_get_contents($str_third_playbill_pool);
        //解析xml为数组对象
        $arr_xml = $this->do_xml($str_content);
        if ($arr_xml["ret"] == 0)
        {
            nn_log::write_log_message(LOG_MODEL_MESSAGE, 'xml解析失败,内容为：' . var_export($arr_xml['data_info'], true));
            return $this->_return_data(1, 'xml解析失败,内容为：' . var_export($str_content, true));
        }
        if (!isset($arr_xml['data']['children']) && !is_array($arr_xml['data']['children'])
            && empty($arr_xml['data']['children']))
        {
            nn_log::write_log_message(LOG_MODEL_MESSAGE, 'xml内容为空：' . var_export($arr_xml['data'], true));
            return $this->_return_data(1, 'xml内容为空：' . var_export($str_content, true));
        }
        //组装数据
        $arr_data = $this->make_completion_content($arr_xml['data']['children'], $result_cp['data_info']);
        @unlink($str_third_playbill_pool);
        return $arr_data;
    }

    /**
     * 获取curl内容
     * @param string $file_path 文件路径
     * @return array
     * @author liangpan
     * @date 2016-03-12
     */
    public function public_get_curl_content($file_path , $time = 30, $file_save_path = null)
    {
        //curl抓取 远程文件的内容
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $file_path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $time);
        $content = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        //如果内容为空  或者根本没这个xml文件
        if (empty($content) || !$content || $http_code >= 400)
        {
            return $this->_return_data(2, "消息：curl下载文件失败地址:" . $file_path . '超时时间:' . $time);
        }
        if (strlen($file_save_path) > 0)
        {
            $save_path = dirname(dirname(dirname(__FILE__))) . '/data/log_v2/iptv/import_xml/' . $this->org_id . '/' . $this->cp_id . '/' . $file_save_path;
            $save_path = str_replace("//", "/", $save_path);
            $path_parts = pathinfo($save_path);
            if (!is_dir($path_parts['dirname']))
            {
                $re = mkdir($path_parts['dirname'], 0777, true);
                if (!$re)
                {
                    return $this->_return_data(2, "文件路径创建失败,路径:" . $path_parts['dirname']);
                }
            }
        }

        return $this->_return_data(0, 'CURL获取成功', $content);
    }

    /**
     * @description:将xml文件转换成数组对象
     * @author:xinxin.deng
     * @date: 2017/9/13 16:51
     * @param $data_xml
     * @return array
     */
    public function do_xml($data_xml)
    {
        $message_content = $this->trim_xml_header($data_xml);
        //解析下载的XML
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->loadXML($message_content);
        $xml = $dom->saveXML();
        $arr_xml = np_xml2array::getArrayData($xml);
        return $arr_xml;
    }

    /**
     * xml 编码转换为UTF-8
     * @param string $xml xml内容
     * @param string $encode 内容编码
     * @return string|mixed
     * @author liangpan
     * @date 2016-03-12
     */
    public function trim_xml_header($xml,$encode=null)
    {
        if(strlen($xml) < 1)
        {
            return '';
        }
        if(strlen($encode) > 0 )
        {
            $xml = mb_convert_encoding($xml,'UTF-8', $encode);
        }
        $xml = preg_replace('/\<\?\s*xml\s+version\s*\=\s*(\"|\').*(\"|\')\s+encoding\s*\=\s*(\"|\')[a-z0-9-]+(\"|\')\s*\?\>/i', '', $xml);
        $xml = preg_replace('/\<\?\s*xml\s+encoding\s*\=\s*(\"|\')[a-z0-9-]+(\"|\')\s*\?\>/i', '', $xml);
        $xml = preg_replace('/\<\?\s*xml\s+version\s*\=\s*(\"|\').*(\"|\')\s*\?\>/i', '', $xml);
        //去除XML中的单引号
// 		$xml = str_replace(array("\'"), "’", $xml);
        return $xml;
    }

    /**
     * @description:对媒资数据进行重新组装、生成、入库
     * @author:xinxin.deng
     * @date: 2017/9/19 11:15
     * @param $xml_arr
     * @param array $cp_data
     * @return array
     */
    public function make_completion_content($xml_arr, $cp_data = array())
    {
        ob_clean();
        foreach ($xml_arr as $key => $val)
        {
            if (!isset($val['children']) || !is_array($val['children']) || empty($val['children']))
            {
                continue;
            }
            $last_val = null;
            foreach ($val['children'] as $k => $v)
            {
                //注入id
                $last_val['nns_asset_import_id'] = $val['attributes']['id'];
                if(!isset($v['name']) || strlen($v['name']) <1 || !isset($last_val['nns_asset_import_id']) || strlen($last_val['nns_asset_import_id']) <1 || ($v['name'] == 'title' && empty($v['content'])))
                {
                    continue 2;
                }
                //名称、拼音、拼音长度
                if ($v['name'] == 'title')
                {
                    $last_val['nns_name'] = htmlspecialchars($v['content'], ENT_QUOTES);
                }
                //为电影的时候，没有片源
                else if($v['name'] == 'relation_pic')
                {
                    $last_val['movie_media'] = isset($v['content']) ? $v['content'] : '';
                }
                //英文名字
                else if ($v['name'] == 'en_title')
                {
                    $last_val['nns_eng_name'] = isset($v['content']) ? $v['content'] : '';
                }
                //地区
                else if ($v['name'] == 'area')
                {
                    $last_val['nns_area'] = isset($v['content']) ? $v['content'] : '';
                }
                //类型，是电影还是电视剧,0电影，1电视剧
                else if ($v['name'] == 'type')
                {
                    $v['content'] = strtolower($v['content']);
                    switch ($v['content'])
                    {
                        case "movie":
                            $last_val['category_name'] = '电影';
                            break;
                        case "drama":
                            $last_val['category_name'] = '电视剧';
                            break;
                        case "competition":
                            $last_val['category_name'] = '赛事';
                            break;
                        case "tvshow":
                            $last_val['category_name'] = '综艺';
                            break;
                    }
                }
                //影片类型
                else if ($v['name'] == 'genre')
                {
                    $last_val['nns_kind'] = isset($v['content']) ? $v['content'] : '';
                }
                //影片时长
                else if ($v['name'] == 'duration')
                {
                    $last_val['nns_view_len'] = (int)$v['content'] > 0 ? (int)$v['content'] * 60 : 0;
                }
                //上映时间
                else if ($v['name'] == 'release_year')
                {
                    $last_val['nns_show_time'] = isset($v['content']) ? $v['content'] : '';
                }
                //总分集数(分片数)
//                 else if ($v['name'] == 'epi_no')
//                 {
//                     $last_val['nns_all_index'] = isset($v['content']) ? $v['content'] : '';
//                 }
                //语种
                else if ($v['name'] == 'language')
                {
                    $last_val['nns_language'] = isset($v['content']) ? $v['content'] : '';
                }
                //简介
                else if ($v['name'] == 'description')
                {
                    $last_val['nns_vod_summary'] = isset($v['content']) ? $v['content'] : '';
                }
                //海报横竖
                else if($v['name'] == 'thumbs' && isset($v['children']) && is_array($v['children']))
                {
                    foreach ($v['children'] as $children_key => $children_val)
                    {
                        if(strpos($children_val['content'], '?') !== false)
                        {
                            $children_val['content'] = preg_replace('/\?.*/i', '', $children_val['content']);
                        }
                        if(isset($children_val['attributes']['size']) && strlen($children_val['attributes']['size'])>0)
                        {
                            $arr_pic_size = explode('x', $children_val['attributes']['size']);
                            if(is_array($arr_pic_size) && !empty($arr_pic_size))
                            {
                                $num = ceil(($arr_pic_size[0]/$arr_pic_size[1])*1000);
                                if ($num < 820)
                                {
                                    $last_val['nns_img_v'] = $children_val['content'];
                                    continue;
                                }
                                else if($num > 1300)
                                {
                                    $last_val['nns_img_h'] = $children_val['content'];
                                    continue;
                                }
                            }
                        }
                    }
                }
                //海报0，1，2，3，4，5
                else if($v['name'] == 'pictures' && isset($v['children']) && is_array($v['children']))
                {
                    $i = 0;
                    foreach ($v['children'] as $children_key => $children_val)
                    {
                        if(strpos($children_val['content'], '?') !== false)
                        {
                            $children_val['content'] = preg_replace('/\?.*/i', '', $children_val['content']);
                        }
                        $last_val['nns_img' . $i] = $children_val['content'];
                        $i ++;
                        if ($i > 5)
                        {
                            break;
                        }
                    }
                }
                //分集描述
                else if($v['name'] =='episodes')
                {
                    $temp_index = $v['children'];
                    $temp_last = null;
                    if(is_array($temp_index) && !empty($temp_index))
                    {
                        foreach ($temp_index as $temp_index_value)
                        {
                            if(!isset($temp_index_value['children'][1]['children']) || !is_array($temp_index_value['children'][1]['children']) || empty($temp_index_value['children'][1]['children']))
                            {
                                continue;
                            }
                            $last_temp_media = null;
                            //配置的片源个数
                            $max_site_num = (int)$this->arr_params['bk_queue_config']['nns_ext_info']['asset_site_num'] > 0 ?
                                (int)$this->arr_params['bk_queue_config']['nns_ext_info']['asset_site_num'] : 3;
                            $media_val_num = 1;
                            foreach ($temp_index_value['children'][1]['children'] as $temp_media_value)
                            {
                                if ($media_val_num > $max_site_num)
                                {
                                    continue;
                                }
                                $last_temp_media[$temp_media_value['children'][0]['content']] = $temp_media_value['children'][1]['content'];
                                $media_val_num ++;
                            }
                            $temp_last[$temp_index_value['children'][0]['content']]=$last_temp_media;
                        }
                    }
                    if(empty($temp_media_value))
                    {
                        continue 2;
                    }
                    $last_val['episodes'] = $temp_last;
                }
                else if($v['name'] =='play_sites')
                {
                    $temp_index = $v['children'];
                    $temp_last = null;
                    if(is_array($temp_index) && !empty($temp_index))
                    {
                        foreach ($temp_index as $temp_index_value)
                        {
                             $temp_last[$temp_index_value['children'][0]['content']] = $temp_index_value['children'][1]['content'];
                        }
                    }
                    if(empty($temp_media_value))
                    {
                        continue 2;
                    }
                    $last_val['play_sites'] = $temp_last;
                }
                // 明星
                else if($v['name'] =='cast_info' && isset($v['children']) && is_array($v['children']))
                {
                    $temp_index_val = array();
                    foreach ($v['children'] as $children_key => $children_val)
                    {
                        if(!is_array($children_val['children']) || empty($children_val['children']))
                        {
                            continue;
                        }
                        foreach ($children_val['children'] as $index_val)
                        {
                            if(!isset($index_val['name']) || $index_val['name'] !='star_name')
                            {
                                continue;
                            }
                            $temp_index_val[] = $index_val['content'];
                        }
                    }
                    $last_val[$v['name']] = $temp_index_val;
                }
                //导演  作者
                else if($v['name'] =='crews' && isset($v['children']) && is_array($v['children']))
                {
                    foreach ($v['children'] as $children_val)
                    {
                        if(!isset($children_val['attributes']['role']) || !in_array($children_val['attributes']['role'], array('writer','director')))
                        {
                            continue;
                        }
                        $temp_index_val = '';
                        if(!is_array($children_val['children']) || empty($children_val['children']))
                        {
                            continue;
                        }

                        foreach ($children_val['children'] as $index_val)
                        {
                            if(!isset($index_val['name']) || $index_val['name'] !='star_name' || !isset($index_val['content']) || strlen($index_val['content']) <1)
                            {
                                continue;
                            }
                            $temp_index_val = $index_val['content'];
                        }
                        $last_val[$children_val['attributes']['role']][] = $temp_index_val;
                    }
                }
            }
            if((!isset($last_val['episodes']) || empty($last_val['episodes']) || !is_array($last_val['episodes'])) && (!isset($last_val['play_sites']) && empty($last_val['play_sites']) || !is_array($last_val['play_sites'])))
            {
                continue;
            }
            $last_val['nns_all_index'] = (isset($last_val['episodes']) && !empty($last_val['episodes']) && is_array($last_val['episodes'])) ? count($last_val['episodes']) : 1;
            if(!isset($last_val['category_name']))
            {
                $last_val['category_name'] = (isset($last_val['episodes']) && !empty($last_val['episodes']) && is_array($last_val['episodes'])) ? "电视剧" : "电影";
            }
            //生产媒资，进行封装
            $asset_data = $this->make_asset($last_val, $cp_data);
            if(empty($asset_data))
            {
                $edit_data = array(
                    'nns_state'=>3,
                    'nns_reason'=>"数据错误",
                );
                $this->msg('执行结果：数据错误' . $edit_data);
                continue;
            }

            //数据加到第三方媒资数据库中
            $result_make_assets = $this->make_assets($asset_data, $cp_data);
            if ($result_make_assets['ret'] == 0)
            {
                $edit_data = array(
                    'nns_state' => 0,
                    'nns_reason'=>"success",
                );
                $this->msg('执行结果：执行成功' . var_export($edit_data, true));
            }
            else
            {
                $this->msg('执行结果：数据执行失败' . var_export($result_make_assets, true));
                //信息'. var_export($asset_data, true).'
                continue;
            }
            unset($last_val);
        }
        return $this->_return_data(0,'ok');
    }

    /**
     * @description:组装主媒资、分集、片源；注：当为电影的时候不进行是否缺片源判断
     * @author:xinxin.deng
     * @date: 2017/9/19 11:18
     * @param $arr_asset_info //传入的媒资信息
     * @param array $cp_data //cp信息
     * @return array array('import_id' => '',//注入id
     *                     'asset_name' => '',//主媒资名称
     *                     'state' => 0,//是否缺片源，0未使用，1缺片源
     *                     'data_info' => array,//最终封装好的主媒资、分集、片源)
     */
    public function make_asset($arr_asset_info,$cp_data = array())
    {
        $video_import_id = $arr_asset_info['nns_asset_import_id'];
        $str_year = (isset($arr_asset_info['nns_show_time']) && !empty($arr_asset_info['nns_show_time'])) ? date("Y", strtotime($arr_asset_info['nns_show_time'])) : date('Y');
        //主媒资信息
        $video_content = array(
            'Name' => $arr_asset_info['nns_name'],
            'CategoryName' => $arr_asset_info['category_name'],
            'ReleaseYear' => $str_year,
            'Kind' => str_replace(' ', '/', $arr_asset_info['nns_kind']),
            'SearchName' => '',
            'DirectorDisplay' => (is_array($arr_asset_info['director']) && !empty($arr_asset_info['director'])) ? implode('/', $arr_asset_info['director']) : '',
            'AliasName' => '',
            'EnglishName' => isset($arr_asset_info['nns_eng_name']) ? $arr_asset_info['nns_eng_name'] : '',
            'ActorDisplay' => (is_array($arr_asset_info['cast_info']) && !empty($arr_asset_info['cast_info'])) ? implode('/', $arr_asset_info['cast_info']) : '',
            'Tags' => '27,28,29,30,31,',
            'OriginalCountry' =>$arr_asset_info['nns_area'],
            'VolumnCount' => isset($arr_asset_info['nns_all_index']) ? (int)$arr_asset_info['nns_all_index'] : 1,
            'bigpic' => '',
            'square_img' => isset($arr_asset_info['nns_img0']) ? $arr_asset_info['nns_img0'] : '',
            'smallpic' => isset($arr_asset_info['nns_img1']) ? $arr_asset_info['nns_img1'] : '',
            'middlepic' => isset($arr_asset_info['nns_img2']) ? $arr_asset_info['nns_img2'] : '',
            'verticality_img' => isset($arr_asset_info['nns_img_v']) ? $arr_asset_info['nns_img_v'] : '',
            'horizontal_img' => isset($arr_asset_info['nns_img_h']) ? $arr_asset_info['nns_img_h'] : '',
            'Description' => isset($arr_asset_info['nns_vod_summary']) ? $arr_asset_info['nns_vod_summary'] : '',
            'WriterDisplay' => (is_array($arr_asset_info['writer']) && !empty($arr_asset_info['writer'])) ? implode('/', $arr_asset_info['writer']) : '',
            'Language' => $arr_asset_info['nns_language'],
            'Duration' => isset($arr_asset_info['nns_view_len']) ? (int)$arr_asset_info['nns_view_len'] : null,
            'thrid_party_info' => '',
        );
        $last_data = array();
        $last_data['video'][] = array(
            'video_id'=>$video_import_id,
            'data'=>$video_content,
        );
        
        if(isset($arr_asset_info['play_sites']) && !empty($arr_asset_info['play_sites']) && is_array($arr_asset_info['play_sites']))
        {
            $arr_site_1 = $arr_site = array();
            while ($k =  key($arr_asset_info['play_sites']))
            {
                $siteid = base64_encode($k);
                $arr_site[$siteid] = $arr_asset_info['play_sites'][$k];
                $arr_site_1[$siteid] = $k;
                next($arr_asset_info['play_sites']);
            }
        
            $index_import_id = $video_import_id . "_" . 0;
            $index_content = array(
                'Sequence' => 1,
                'Name' => $video_content['Name'],
                'Duration' => isset($arr_asset_info['nns_view_len']) ? $arr_asset_info['nns_view_len'] : 0,
                'Description' => '',
                'WriterDisplay' => $video_content['WriterDisplay'],
                'ActorDisplay' => $video_content['ActorDisplay'],
                'ViewPoint' => '',
                'Tags' => '27,28,29,30,31,',
                'Language' => $video_content['Language'],
                'OriginalCountry' => $video_content['OriginalCountry'],
                'KeyWords' => '',
                'ReleaseYear' => $str_year,
                'pic' => '',
                'thrid_party_info' => array_keys($arr_site),
            );
            $last_data['index'][] = array(
                'video_id' => $video_import_id,
                'index_id' => $index_import_id,
                'data' => $index_content,
            );
            //片源
            $media_import_id = $index_import_id . "_media";
            $media_content = array(
                'Name' => $video_content['Name'],
                'MediaMode' => 'hd',
                'Resolution' => 6,
                'FileSize' => '8081',
                'BitRateType' => '4097',
                'Duration' => isset($arr_asset_info['nns_view_len']) ? $arr_asset_info['nns_view_len'] : 0,
                'VideoType' => 'H264',
                'FileURL' => '',
                'Tags' => '27,28,29,30,31,',
                'conf_info' => array('import_cdn_mode' => 'weburl'),
                'thrid_party_playurls' => $arr_site,
            );
            $last_data['media'][] = array(
                'video_id' => $video_import_id,
                'index_id' => $index_import_id,
                'media_id' => $media_import_id,
                'data' => $media_content,
            );
        }
        else if(isset($arr_asset_info['episodes']) && is_array($arr_asset_info['episodes']) && !empty($arr_asset_info['episodes']))
        {
            $index = 0;
            foreach ($arr_asset_info['episodes'] as $key => $val)
            {
                $index++;
                if(preg_match ("/\d{4}-1[0-2]|0?[1-9]-0?[1-9]|[12][0-9]|3[01]/", $key))
                {
                    $str_name = '期';
                }
                else
                {
                    if ($index > 250)
                    {
                        continue;
                    }
//                     $index = $key;
//                     $index++;
                    $str_name = '集';
                }
                $arr_site_1 = $arr_site = array();
                if (is_array($val))
                {
                    while ($k =  key($val))
                    {
                        $siteid = base64_encode($k);
                        $arr_site[$siteid] = $val[$k];
                        $arr_site_1[$siteid] = $k;
                        next($val);
                    }
                }
            
                
                $index_import_id = $video_import_id . "_" . $key;
                $index_content = array(
                    'Sequence' => $index,
                    'Name' => $video_content['Name'] . "第{$key}{$str_name}",
                    'Duration' => isset($arr_asset_info['nns_view_len']) ? $arr_asset_info['nns_view_len'] : 0,
                    'Description' => '',
                    'WriterDisplay' => $video_content['WriterDisplay'],
                    'ActorDisplay' => $video_content['ActorDisplay'],
                    'ViewPoint' => '',
                    'Tags' => '27,28,29,30,31,',
                    'Language' => $video_content['Language'],
                    'OriginalCountry' => $video_content['OriginalCountry'],
                    'KeyWords' => '',
                    'ReleaseYear' => $str_year,
                    'pic' => '',
                    'thrid_party_info' => array_keys($arr_site),
                );
                $last_data['index'][] = array(
                    'video_id' => $video_import_id,
                    'index_id' => $index_import_id,
                    'data' => $index_content,
                );
                //片源
                $media_import_id = $index_import_id . "_media";
                $media_content = array(
                    'Name' => $video_content['Name'] . "第{$key}{$str_name}",
                    'MediaMode' => 'hd',
                    'Resolution' => 6,
                    'FileSize' => '8081',
                    'BitRateType' => '4097',
                    'Duration' => isset($arr_asset_info['nns_view_len']) ? $arr_asset_info['nns_view_len'] : 0,
                    'VideoType' => 'H264',
                    'FileURL' => '',
                    'Tags' => '27,28,29,30,31,',
                    'conf_info' => array('import_cdn_mode' => 'weburl'),
                    'thrid_party_playurls' => $arr_site,
                );
                $last_data['media'][] = array(
                    'video_id' => $video_import_id,
                    'index_id' => $index_import_id,
                    'media_id' => $media_import_id,
                    'data' => $media_content,
                );
            }
        }
        else
        {
            return null;
        }
        if(isset($arr_site_1) && is_array($arr_site_1) && !empty($arr_site_1))
        {
            foreach ($arr_site_1 as $site_key_1=>$site_name)
            {
                $result_exsist_site = nl_full_assets_site::query_unique($this->obj_dc, "nns_siteid='{$site_key_1}'");
                if(isset($result_exsist_site['data_info']) && is_array($result_exsist_site['data_info']) && !empty($result_exsist_site['data_info']))
                {
                    continue;
                }
                nl_full_assets_site::add($this->obj_dc, array('nns_id'=>np_guid_rand(),'nns_siteid'=>$site_key_1,'nns_name'=>$site_name,'nns_state'=>0,'nns_img'=>''));
            }
        }
        if(!isset($last_data['index']) || empty($last_data['index']) || !is_array($last_data['index']) || !isset($last_data['media']) || empty($last_data['media']) || !is_array($last_data['media']))
        {
            return null;
        }
        
        $data = array(
            'import_id' => $video_import_id,
            'asset_name' => $arr_asset_info['nns_name'],
            'state' => 0,
            'data_info' => $last_data,
        );
        return $data;
    }

    /**
     * @description:加入到第三方媒资数据库中
     * @author:xinxin.deng
     * @date: 2017/9/19 21:46
     * @param $assets_data
     * @param $cp_data
     * @return Ambigous|array
     */
    public function make_assets($assets_data, $cp_data)
    {
        if (!isset($assets_data) && !is_array($assets_data))
        {
            return $assets_data;
        }
        $date = date('Y-m-d H:i:s');
        $nns_asset_import_id = $assets_data['import_id'];
        $nns_asset_id = md5($cp_data['nns_id'].'|'.$assets_data['asset_name']);
        $nns_asset_id = md5($nns_asset_id.'|'.$assets_data['asset_name'].'|'.$cp_data['nns_id']);
        //封装数据
        $data = array(
            'nns_id' => np_guid_rand(),
            'nns_asset_id' => $nns_asset_id,
            'nns_asset_import_id' => $nns_asset_import_id,
            'nns_asset_name' => $assets_data['asset_name'],
            'nns_content' => base64_encode(json_encode($assets_data['data_info'])),
            'nns_cp_id' => $cp_data['nns_id'],
            'nns_state' => $assets_data['state'],
            'nns_create_time' => $date,
            'nns_modify_time' => $date,
        );

        //查询是否已经加入
        $result_unique = nl_full_assets::query_unique($this->obj_dc, "where nns_asset_id='{$nns_asset_id}' AND nns_cp_id = '{$cp_data['nns_id']}' limit 1");

        if ($result_unique['ret'] != 0)
        {
            return $result_unique;
        }
        if (isset($result_unique['data_info'][0]) && is_array($result_unique['data_info'][0]) && !empty($result_unique['data_info'][0]))
        {
            if(md5($data['nns_content']) == md5($result_unique['data_info'][0]['nns_content']))
            {
                return $this->_return_data('1', '数据已经存在不做任何改变,媒资id为：' . $nns_asset_id . '名称为：' . $assets_data['asset_name']);
            }
            else
            {
                $result = nl_full_assets::edit($this->obj_dc, array('nns_content'=>$data['nns_content'],'nns_state'=>$assets_data['state']), $result_unique['data_info'][0]['nns_id']);
                $result['ret'] = "数据已经存在但是要做修改".$result['ret'];
                return $result;
            }
            
        }
        //加入数据
        $re_add = nl_full_assets::add($this->obj_dc, $data);
        return $re_add;
    }

    /**
     * @description:直接组装主媒资、分集、片源可以直接入库 ------（暂时没用）
     * @author:xinxin.deng
     * @date: 2017/9/18 17:17
     * @param $arr_asset_info 媒资信息
     * @param $cp_id cp ID
     * @return mixed
     */
    public function make_asset_v2($arr_asset_info, $cp_data = array())
    {
        $video_import_id = $arr_asset_info['nns_asset_import_id'];
        $str_year = (isset($arr_asset_info['nns_show_timeindex']) && !empty($arr_asset_info['nns_show_timeindex'])) ? date("Y",strtotime($arr_asset_info['nns_show_timeindex'])) : date('Y');
        $video_content = array(
            'nns_name' => $arr_asset_info['nns_name'],
            'nns_state' => $arr_asset_info['nns_state'],
            'nns_show_timeindex' => $str_year,
            'nns_pinyin' => $arr_asset_info['nns_pinyin'],
            'nns_pinyin_length' => $arr_asset_info['nns_pinyin_length'],
            'nns_all_index' => isset($arr_asset_info['nns_pinyin_length']) ? (int)$arr_asset_info['nns_pinyin_length'] : null,
            'nns_kind' => str_replace(' ', '/', $arr_asset_info['nns_kind']),
            'nns_screenwriter' => (is_array($arr_asset_info['writer']) && !empty($arr_asset_info['writer'])) ? implode('/', $arr_asset_info['writer']) : '',
            'nns_alias_name' => '',
            'nns_eng_name' => isset($arr_asset_info['nns_eng_name']) ? $arr_asset_info['nns_eng_name'] : '',
            'nns_actor' => (is_array($arr_asset_info['nns_actor']) && !empty($arr_asset_info['nns_actor'])) ? implode('/', $arr_asset_info['nns_actor']) : '',
            'nns_tag' => '27,28,29,30,31,',
            'nns_area'=>$arr_asset_info['nns_area'],
            'nns_image0' => isset($arr_asset_info['nns_image0']) ? $arr_asset_info['nns_image0'] : '',
            'nns_image1' => isset($arr_asset_info['nns_image1']) ? $arr_asset_info['nns_image1'] : '',
            'nns_image2' => isset($arr_asset_info['nns_image2']) ? $arr_asset_info['nns_image2'] : '',
            'nns_image3' => isset($arr_asset_info['nns_image3']) ? $arr_asset_info['nns_image3'] : '',
            'nns_image4' => isset($arr_asset_info['nns_image4']) ? $arr_asset_info['nns_image4'] : '',
            'nns_image5' => isset($arr_asset_info['nns_image5']) ? $arr_asset_info['nns_image5'] : '',
            'nns_image_v' => isset($arr_asset_info['nns_image_v']) ? $arr_asset_info['nns_image_v'] : '',
            'nns_image_h' => isset($arr_asset_info['nns_image_v']) ? $arr_asset_info['nns_image_v'] : '',
            'nns_vod_summary' => isset($arr_asset_info['nns_vod_summary']) ? $arr_asset_info['nns_vod_summary'] : '',
            'nns_director' => (is_array($arr_asset_info['director']) && !empty($arr_asset_info['director'])) ? implode('/', $arr_asset_info['director']) : '',
            'nns_language' => $arr_asset_info['nns_language'],
            'nns_cp_id' => $cp_data['nns_id'],
            'nns_view_len' => isset($arr_asset_info['nns_view_len']) ? (int)$arr_asset_info['nns_view_len'] : null,
        );
        $last_data['video'][] = array(
            'video_id'=>$video_import_id,
            'data'=>$video_content,
        );
        //分集
        if (isset($arr_asset_info['index']) && !empty($arr_asset_info['index']) && is_array($arr_asset_info['index']))
        {
            foreach ($arr_asset_info['index'] as $key=>$val)
            {
                $str_name = '集';
                $index_import_id = $video_import_id."_".$key;
                $index_content=array(
                    'nns_index'=>$key,
                    'nns_name'=>$arr_asset_info['nns_name']."第{$key}{$str_name}",
                    'nns_time_len'=>isset($arr_asset_info['nns_view_len']) ? $arr_asset_info['nns_view_len']: 0,
                    'nns_summary'=>'',
                    'nns_director'=>$video_content['nns_director'],
                    'nns_actor'=>$video_content['nns_actor'],
                    'nns_release_time'=>$str_year,
                    'nns_cp_id' => $cp_data['nns_id'],
                    'pic'=>'',
                );
                $last_data['index'][] = array(
                    'video_id'=>$video_import_id,
                    'index_id'=>$index_import_id,
                    'data'=>$index_content,
                );

                //分集下的片源
                if (isset($val['play_sites']) && is_array($val['play_sites']) && !empty($val['play_sites']))
                {
                    $media_num = 0;
                    foreach ($val['play_sites'] as $m_k => $m_v)
                    {
                        $media_import_id = $index_import_id."_media_". $media_num;
                        $media_content=array(
                            'nns_name' => $video_content['nns_name']."第{$key}{$str_name}",
                            'nns_media_name' => $m_v['name'],
                            'nns_mode' => 'hd',
                            'nns_re' => 6,
                            'nns_file_size' => '8081',
                            'nns_kbps' => '4097',
                            'Duration' => $arr_asset_info['video']['duration'],
                            'nns_file_coding' => 'H264',
                            'nns_url' => $m_v['url'],
                            'nns_tag'=>'27,28,29,30,31,',
                            'nns_cp_id' => $cp_data['nns_id'],
                            'nns_conf_info' => array('import_cdn_mode'=>$cp_data['nns_id']),
                        );
                        $last_data['media'][] = array(
                            'video_id'=>$video_import_id,
                            'index_id'=>$index_import_id,
                            'media_id'=>$media_import_id,
                            'data'=>$media_content,
                        );
                        $media_num ++;
                    }
                }
            }
        }
        return $last_data;
    }

}
$arr_files = pathinfo(__FILE__);
$file_name = $arr_files['filename'];
$timer_execute = new timer_execute($file_name, $file_name,__FILE__,'thrid_full_assests_v3');
$timer_execute->run();
